package org.sky.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
	private static final String base_path="";
	/**
	 * 写入文件
	 * @param filePath 文件路径
	 * @param data 内容
	 * @param flag 类型 true追加  false是覆盖原有内容
	 */
	public static void  writeFile(String filePath,String data,boolean flag){
		try {
			File file =new File(filePath);
		    if(!file.exists()){
		    	file.createNewFile();
		    }
		    FileWriter fileWritter = new FileWriter(file.getAbsoluteFile(),flag);

            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write(data);
            bufferWritter.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	public static void  writeFile(String filePath,String data){
		try {
			File file =new File(filePath);
		    if(!file.exists()){
		    	file.createNewFile();
		    }
//		    OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"gb2312");
		    OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"utf-8");
			BufferedWriter writer=new BufferedWriter(write);  			
			writer.write(data);
			writer.close(); 
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	public static void creatDirs(String filePath){
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdirs();
		}
	}
	
	 public static void deleteFile(String filePath){
			String basePath = base_path;
			File file = new File(basePath+filePath);
			if(file.exists()){
				file.delete();
			}
		}
	    public static void delAllFile(String filepath,boolean flag){
	    	del(filepath);
	    	if(flag){
	    		deleteFile(filepath);
	    	}
	    }
	    /**
	     * 
	     * @param filepath
	     * @throws IOException
	     */
	    public static void del(String filepath) {
	    	try {
	    		File f = new File(filepath);// 定义文件路径
	            if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
	                if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
	                    f.delete();
	                } else {// 若有则把文件放进数组，并判断是否有下级目录
	                    File delFile[] = f.listFiles();
	                    int i = f.listFiles().length;
	                    for (int j = 0; j < i; j++) {
	                        if (delFile[j].isDirectory()) {
	                            del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
	                        }
	                        delFile[j].delete();// 删除文件
	                    }
	                }
	            }
			} catch (Exception e) {
				
				e.printStackTrace();
			}
	        
	    }
	/**
	 * 将临时文件转移到正式目录
	 * @param model
	 * @return
	 */
	public static String copyFile(String oldPath,String saveDic){
		if(oldPath!=null && !"".equals(oldPath)){
			String basePath = base_path;
			
			String tarPath = "";
			File file = new File(basePath + oldPath);
			if(file.exists()){
				String name = file.getName();				
				tarPath = saveDic + File.separatorChar + name;
				
				File tarDicFile = new File(basePath+saveDic); 
				if(!tarDicFile.exists()){
					tarDicFile.mkdirs();
				}
				File tarFile = new File(basePath+tarPath);
				copyFile(file, tarFile);
				file.delete();
				
				return tarPath.replace("\\", "/");
			}			
		}	
		return null;
				
	}
	// 复制文件
    public static void copyFile(File sourceFile, File targetFile)  {

        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {

            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        }catch(Exception e){
        	e.printStackTrace();
        } finally {
            // 关闭流
        	try {
                if (inBuff != null)
                    inBuff.close();
                if (outBuff != null)
                    outBuff.close();
			} catch (IOException e2) {
				
				e2.printStackTrace();
			}

        }
    }
    // 复制文件夹
    public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
        // 新建目标目录
        (new File(targetDir)).mkdirs();
        // 获取源文件夹当前下的文件或目录
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                // 源文件
                File sourceFile = file[i];
                // 目标文件
                File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
                copyFile(sourceFile, targetFile);
            }
            if (file[i].isDirectory()) {
                // 准备复制的源文件夹
                String dir1 = sourceDir + "/" + file[i].getName();
                // 准备复制的目标文件夹
                String dir2 = targetDir + "/" + file[i].getName();
                copyDirectiory(dir1, dir2);
            }
        }
    }
    /**
     * copy除指定文件以外的所有文件(copy文件夹)
     * @param sourceDir
     * @param targetDir
     */
    public static void copyDirectiory(String sourceDir, String targetDir, String appointFile) throws IOException {
        // 新建目标目录
        (new File(targetDir)).mkdirs();
        // 获取源文件夹当前下的文件或目录
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                // 源文件
                File sourceFile = file[i];
                if(!sourceFile.getName().equals(appointFile) && !sourceFile.getName().toLowerCase().endsWith(".ftl")){
                	// 目标文件
                    File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
                    copyFile(sourceFile, targetFile);
                }                
            }
//            if (file[i].isDirectory()) {
//                if(!file[i].getName().equals("demo")){
//                	// 准备复制的源文件夹
//                    String dir1 = sourceDir + "/" + file[i].getName();
//
//                    // 准备复制的目标文件夹
//                    String dir2 = targetDir + "/" + file[i].getName();
//                    copyDirectiory(dir1, dir2);
//                }                
//            }
        }
    }
    /**
     * 
     * @param srcFileName
     * @param destFileName
     * @param srcCoding
     * @param destCoding
     * @throws IOException
     */
    public static void copyFile(File srcFileName, File destFileName, String srcCoding, String destCoding) throws IOException {// 把文件转换为GBK文件
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName), srcCoding));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFileName), destCoding));
            char[] cbuf = new char[1024 * 5];
            int len = cbuf.length;
            int off = 0;
            int ret = 0;
            while ((ret = br.read(cbuf, off, len)) > 0) {
                off += ret;
                len -= ret;
            }
            bw.write(cbuf, 0, off);
            bw.flush();
        } finally {
            if (br != null)
                br.close();
            if (bw != null)
                bw.close();
        }
    }
   
    
    /**
     * 读取某个文件夹下的所有文件，返回指定后缀文件的文件名
     */
    public static void readfile(String filepath,String suffixName,List list) throws FileNotFoundException, IOException {
    	try {
    		File file = new File(filepath);
    		if (file.isDirectory()) {                
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                	String fileName = filelist[i];
                	File readfile = new File(filepath + File.separatorChar + filelist[i]);
                    if (!readfile.isDirectory()) {
                    	String suffix = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : null;
                    	if(suffixName.equals(suffix)){                     		
                    		String path=readfile.getParentFile().getName()+"//"+fileName;
                    		list.add(path);
                    	}
                    } else if (readfile.isDirectory()) {
                         readfile(filepath + File.separatorChar + filelist[i],suffixName,list);
                    }
                }
    		}
    	} catch (FileNotFoundException e) {
    		System.out.println("readfile()   Exception:" + e.getMessage());
    	}
  
    }
    
    public static void main(String[]args){
    	try {
    		List list = new ArrayList();
//    		readfile("E:\\boss.resource.com\\template\\ED72099C5844C952270E8E3C1D8B82A5", ".ftl",list);
    		writeFile("E:\\home\\boss_ujoy_com_logs.log", "111111", false);
//			System.out.println(list.get(0));
		} catch (Exception e) {
			
			e.printStackTrace();
		}
    }
}
